package com.kwshare.gateway.filter;

import com.kwshare.common.core.utils.JwtUtils;
import com.kwshare.common.core.utils.StringUtils;
import com.kwshare.gateway.config.properties.IgnoreWhiteProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * 网关鉴权过滤器
 *
 * @author yangjing
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    /** 授权 */
    public static final String AUTHENTICATION = "Authorization";

    /** 白名单 */
    @Resource
    private IgnoreWhiteProperties ignoreWhite;

    /**
     * 过滤器
     * @param exchange exchange
     * @param chain chain
     * @return 结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("网关过滤器执行...");
        // 响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 请求对象
        ServerHttpRequest request = exchange.getRequest();
        // url
        String url = request.getURI().getPath();
        // 放行白名单
        if(StringUtils.matches(url,ignoreWhite.getWhites())){
            return chain.filter(exchange);
        }
        // 响应消息
        String msg = null;
        // token
        String token = exchange.getRequest().getHeaders().getFirst(AUTHENTICATION);
        token = token.replaceFirst("Bearer ","");
        // 拦截token
        if(token==null){
            msg = "{ \"code\":401,\"message\":\"没有权限！\" }";
            // 设置状态码
            response.setStatusCode(HttpStatus.OK);
            // 设置请求头
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            // 构建DataBuffer对象
            DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(wrap));
        }
        try{
            JwtUtils.parseToken(token);
        }catch (Exception e){
            msg = "{ \"code\":401,\"message\":\"令牌已过期或验证不正确！\" }";
            // 设置状态码
            response.setStatusCode(HttpStatus.OK);
            // 设置请求头
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            // 构建DataBuffer对象
            DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(wrap));
        }
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 过滤器执行顺序
     *
     * @return 执行顺序
     */
    @Override
    public int getOrder() {
        return -200;
    }
}
